#!/usr/bin/env python3
"""
KidsBuddy 1.0 用户模型演示
展示用户模型的创建、管理和关系功能
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from kidsbuddy.models.user import (
    Child, Parent, LearningStyle, SRLLevel, Grade, 
    LearningPreferences, ParentalSettings
)
from kidsbuddy.models.relationships import (
    RelationshipManager, RelationshipType, PermissionLevel, Permission
)
from kidsbuddy.data.user_repository import UserRepository
import tempfile
import shutil


def demo_child_creation():
    """演示儿童用户创建和管理"""
    print("=" * 60)
    print("🧒 儿童用户创建和管理演示")
    print("=" * 60)
    
    # 创建儿童用户
    child = Child(
        name="小明",
        age=8,
        grade=Grade.GRADE_2,
        learning_style=LearningStyle.VISUAL
    )
    
    print(f"✅ 创建儿童用户: {child.name}")
    print(f"   ID: {child.id}")
    print(f"   年龄: {child.age}岁")
    print(f"   年级: {child.grade.value}")
    print(f"   学习风格: {child.learning_style.value}")
    print(f"   SRL水平: {child.srl_level.value}")
    
    # 更新SRL评分
    print("\n📊 更新SRL评分...")
    child.srl_profile.goal_setting_score = 75.0
    child.srl_profile.planning_score = 70.0
    child.srl_profile.monitoring_score = 68.0
    child.srl_profile.evaluation_score = 72.0
    child.srl_profile.reflection_score = 65.0
    child.srl_profile.strategy_use_score = 70.0
    child.srl_profile.motivation_regulation_score = 73.0
    
    child.update_srl_level()
    print(f"   总体SRL评分: {child.srl_profile.overall_srl_score:.1f}")
    print(f"   SRL水平: {child.srl_level.value}")
    
    # 更新任务水平
    print("\n📚 更新学习任务水平...")
    child.update_task_level("reading_aloud", 6)
    child.update_task_level("writing", 5)
    child.update_task_level("memorization", 7)
    
    print(f"   朗读水平: {child.reading_aloud_level}/10")
    print(f"   写作水平: {child.writing_level}/10")
    print(f"   背诵水平: {child.memorization_level}/10")
    print(f"   平均任务水平: {child.average_task_level:.1f}/10")
    
    return child


def demo_parent_creation():
    """演示家长用户创建和管理"""
    print("\n" + "=" * 60)
    print("👨‍👩‍👧‍👦 家长用户创建和管理演示")
    print("=" * 60)
    
    # 创建家长用户
    parent = Parent(
        name="张三",
        email="zhangsan@example.com",
        phone="13800138000"
    )
    
    print(f"✅ 创建家长用户: {parent.name}")
    print(f"   ID: {parent.id}")
    print(f"   邮箱: {parent.email}")
    print(f"   手机: {parent.phone}")
    print(f"   验证状态: {'已验证' if parent.is_verified else '未验证'}")
    
    # 验证身份
    print("\n🔐 验证家长身份...")
    parent.verify_identity("email")
    print(f"   验证状态: {'已验证' if parent.is_verified else '未验证'}")
    print(f"   验证方式: {parent.verification_method}")
    
    # 更新家长设置
    print("\n⚙️ 更新家长控制设置...")
    parent.update_settings(
        daily_time_limit_minutes=90,
        content_filter_level="high",
        notification_enabled=True
    )
    
    settings = parent.parental_settings
    print(f"   每日时间限制: {settings.daily_time_limit_minutes}分钟")
    print(f"   内容过滤级别: {settings.content_filter_level}")
    print(f"   通知启用: {settings.notification_enabled}")
    
    # 添加紧急联系人
    print("\n🚨 添加紧急联系人...")
    parent.add_emergency_contact("李四", "13900139000", "朋友")
    print(f"   紧急联系人数量: {len(parent.emergency_contacts)}")
    
    return parent


def demo_user_repository():
    """演示用户数据仓库功能"""
    print("\n" + "=" * 60)
    print("💾 用户数据仓库演示")
    print("=" * 60)
    
    # 创建临时目录用于演示
    temp_dir = tempfile.mkdtemp()
    repository = UserRepository(temp_dir)
    
    try:
        # 创建并保存儿童用户
        child = Child(name="演示儿童", age=7, learning_style=LearningStyle.AUDITORY)
        saved_child = repository.create_child(child)
        print(f"✅ 保存儿童用户: {saved_child.name} (ID: {saved_child.id})")
        
        # 创建并保存家长用户
        parent = Parent(name="演示家长", email="demo@example.com")
        saved_parent = repository.create_parent(parent)
        print(f"✅ 保存家长用户: {saved_parent.name} (ID: {saved_parent.id})")
        
        # 建立家长-儿童关系
        success = repository.link_parent_child(saved_parent.id, saved_child.id, "parent")
        if success:
            print(f"✅ 建立家长-儿童关系: {saved_parent.name} -> {saved_child.name}")
        
        # 查询用户
        retrieved_child = repository.get_child(saved_child.id)
        retrieved_parent = repository.get_parent_by_email("demo@example.com")
        
        print(f"🔍 查询儿童用户: {retrieved_child.name if retrieved_child else '未找到'}")
        print(f"🔍 通过邮箱查询家长: {retrieved_parent.name if retrieved_parent else '未找到'}")
        
        # 列出所有用户
        all_children = repository.list_children()
        all_parents = repository.list_parents()
        
        print(f"📋 儿童用户总数: {len(all_children)}")
        print(f"📋 家长用户总数: {len(all_parents)}")
        
        # 验证关系
        if retrieved_child and retrieved_parent:
            print(f"👨‍👧 家长的子女: {retrieved_parent.children_ids}")
            print(f"👧‍👨 儿童的家长: {retrieved_child.parent_ids}")
        
    finally:
        # 清理临时目录
        shutil.rmtree(temp_dir)
        print("🧹 清理临时数据")


def demo_relationship_management():
    """演示关系管理功能"""
    print("\n" + "=" * 60)
    print("🔗 用户关系管理演示")
    print("=" * 60)
    
    manager = RelationshipManager()
    
    # 创建关系
    relationship = manager.create_relationship(
        "parent_12345678",
        "child_87654321",
        RelationshipType.PARENT,
        PermissionLevel.FULL
    )
    
    print(f"✅ 创建关系: {relationship.relationship_type.value}")
    print(f"   从用户: {relationship.from_user_id}")
    print(f"   到用户: {relationship.to_user_id}")
    print(f"   权限级别: {relationship.permission_level.value}")
    print(f"   权限数量: {len(relationship.permissions)}")
    
    # 验证关系
    relationship.verify_relationship("admin_12345678")
    print(f"   验证状态: {'已验证' if relationship.is_verified else '未验证'}")
    
    # 检查权限
    permissions_to_check = [
        Permission.VIEW_LEARNING_DATA,
        Permission.EDIT_LEARNING_SETTINGS,
        Permission.MANAGE_PARENTAL_CONTROLS,
        Permission.EMERGENCY_ACCESS
    ]
    
    print("\n🔐 权限检查:")
    for permission in permissions_to_check:
        has_permission = manager.check_permission(
            "parent_12345678",
            "child_87654321",
            permission
        )
        status = "✅" if has_permission else "❌"
        print(f"   {status} {permission.value}")


def demo_data_serialization():
    """演示数据序列化功能"""
    print("\n" + "=" * 60)
    print("📄 数据序列化演示")
    print("=" * 60)
    
    # 创建复杂的儿童用户
    child = Child(
        name="序列化测试",
        age=9,
        grade=Grade.GRADE_3,
        learning_style=LearningStyle.KINESTHETIC
    )
    
    # 设置一些数据
    child.srl_profile.goal_setting_score = 80.0
    child.update_task_level("reading_comprehension", 8)
    child.add_study_session(45)  # 45分钟学习会话
    
    # 序列化为字典
    child_dict = child.to_dict()
    print(f"✅ 儿童用户序列化完成")
    print(f"   字典键数量: {len(child_dict)}")
    print(f"   包含SRL档案: {'srl_profile' in child_dict}")
    print(f"   包含学习偏好: {'learning_preferences' in child_dict}")
    
    # 从字典反序列化
    child_from_dict = Child.from_dict(child_dict)
    print(f"✅ 从字典反序列化完成")
    print(f"   姓名匹配: {child.name == child_from_dict.name}")
    print(f"   年龄匹配: {child.age == child_from_dict.age}")
    print(f"   SRL评分匹配: {child.srl_profile.goal_setting_score == child_from_dict.srl_profile.goal_setting_score}")
    
    # 家长用户序列化
    parent = Parent(name="序列化家长", email="serialize@example.com")
    parent.add_child(child.id, "parent")
    
    parent_dict = parent.to_dict()
    parent_from_dict = Parent.from_dict(parent_dict)
    
    print(f"✅ 家长用户序列化完成")
    print(f"   子女数量匹配: {len(parent.children_ids) == len(parent_from_dict.children_ids)}")


def main():
    """主演示函数"""
    print("🎉 KidsBuddy 用户模型功能演示")
    print("=" * 60)
    
    try:
        # 演示各个功能模块
        child = demo_child_creation()
        parent = demo_parent_creation()
        
        # 建立家长-儿童关系
        print("\n🔗 建立家长-儿童关系...")
        parent.add_child(child.id, "parent")
        child.parent_ids.append(parent.id)
        print(f"   {parent.name} 现在是 {child.name} 的家长")
        
        demo_user_repository()
        demo_relationship_management()
        demo_data_serialization()
        
        print("\n" + "=" * 60)
        print("🎊 演示完成！所有功能正常工作。")
        print("=" * 60)
        
    except Exception as e:
        print(f"\n❌ 演示过程中出现错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
